<template>
  <div>
     <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
     </el-breadcrumb>
   <el-card>
       <!-- 提示信息 -->
       <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable='false'
        show-icon>
       </el-alert>

       <!-- 选择商品分类的级联框 -->
       <div style="margin:15px 0;">
           选择商品分类：
           <el-cascader
            v-model="selectOptionArr"
            :options="cascaderList"
            :props="cascaderProps"
            @change="cascaderHandleChange">
           </el-cascader>
       </div>

       <!-- 动态参数和静态属性的tab栏切换 -->
        <el-tabs v-model="activeName" @tab-click="tabsHandleClick">
             <!-- 1. 动态参数 -->
            <el-tab-pane label="动态参数" name="many">
                <el-button @click="addParamsDialogVisible=true" size='mini' type='primary' :disabled='isBtnDisable'>添加参数</el-button>
                 <!-- 动态分类参数列表展示 -->
                <el-table :data='manyTableList' border stripe style="width: 100%">
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag closable v-for="(item,i) in scope.row.attr_vals" :key='i'
                            @close="removeAttr(i,scope.row)">
                                {{item}}
                            </el-tag>
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                style="width:120px;">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button @click="showEditParamsDialog(scope.row)" type='primary' size='mini' icon="el-icon-edit">编辑</el-button>
                            <el-button @click="removeParams(scope.row)" type='danger' size='mini' icon="el-icon-delete">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>

            <!-- 2. 静态属性 -->
            <el-tab-pane label="静态属性" name="only">
                <el-button @click="addParamsDialogVisible=true" size='mini' type='primary' :disabled='isBtnDisable'>添加属性</el-button>
                 <!-- 静态分类参数列表展示 -->
                <el-table :data='onlyTableList' border stripe style="width: 100%">
                    <el-table-column type="expand">
                         <template slot-scope="scope">
                            <el-tag closable v-for="(item,i) in scope.row.attr_vals" :key='i'
                            @close="removeAttr(i,scope.row)"
                            >
                                {{item}}
                            </el-tag>
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                style="width:120px;"
                                >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button @click="showEditParamsDialog(scope.row)" type='primary' size='mini' icon="el-icon-edit">编辑</el-button>
                            <el-button @click="removeParams(scope.row)" type='danger' size='mini' icon="el-icon-delete">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
   </el-card>

   <!--添加参数和属性的公用对话框  -->
   <el-dialog
        @close='addParamsDialogClose'
        :title="activeName=='only'?'添加静态属性':'添加动态参数'"
        :visible.sync="addParamsDialogVisible"
        width="50%">
        <!--表单输入框 ,ref是能够获取到当前组件 -->
        <el-form :model="addParamsForm" :rules="editParamsRules" ref="addParamsRef" label-width="100px" class="demo-ruleForm">
            <!-- prop属性是需要验证的字段名 -->
            <el-form-item :label="activeName=='only'?'静态属性':'动态参数'" prop="attr_name">
                <el-input v-model="addParamsForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addParamsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParamsSub">确 定</el-button>
        </span>
    </el-dialog>
    
    <!-- 编辑按钮对话框 -->
    <el-dialog
        @close='editParamsDialogClose'
        :title="activeName=='only'?'修改静态属性':'修改动态参数'"
        :visible.sync="editParamsDialogVisible"
        width="50%">
        <!--表单输入框 ,ref是能够获取到当前组件 -->
        <el-form :model="editParamsForm" :rules="editParamsRules" ref="editParamsRef" label-width="100px" class="demo-ruleForm">
            <!-- prop属性是需要验证的字段名 -->
            <el-form-item :label="activeName=='only'?'静态属性':'动态参数'" prop="attr_name">
                <el-input v-model="editParamsForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editParamsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParamsSub()">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {

  data () {
    return {
        // 用于保存option的数据源
        cascaderList:[],
        // 保存选择项数据
        selectOptionArr:[],
        // 保存配置选项props的数据
        cascaderProps:{
            expandTrigger: 'hover',
            label:'cat_name',
            value:'cat_id',
        },
        // 保存用户选择的是参数还是属性,only表示静态属性,many表示动态参数
        activeName:'many',
        // 保存静态参数
        onlyTableList:[],
        // 保存动态参数
        manyTableList:[],
        // 控制添加动态参数和静态属性对话框的显示与隐藏
        addParamsDialogVisible:false,
        // 保存添加对话框表单数据
        addParamsForm:{
            attr_name:''
        },
        // 添加对话框表单校验规则
        addParamsRules:{
            attr_name:[
                { required: true, message: '请输入参数名称', trigger: 'blur' },
            ]
        },
        // 编辑按钮对话框的显示与隐藏
        editParamsDialogVisible:false,
        // 保存编辑对话框表单数据
        editParamsForm:{
            attr_name:''
        },
        // 编辑对话框的验证规则
        editParamsRules:{
            attr_name:[
                { required: true, message: '请输入参数名称', trigger: 'blur' },
            ]
        },

        // // 控制输入框和按钮显示与隐藏
        // inputVisible:false,
        // // 双向数据绑定
        // inputValue:''
    }
  },

  methods: {
    //   级联框中的获取分类数据
      async getcascaderList(){
          const res=await this.axios.get('categories');
          if(res.meta.status==200){
              this.cascaderList=res.data
          }
        //   console.log(this.cascaderList);
      },

    //   获取参数列表
      async getParams(){
        if(this.selectOptionArr.length != 3){
            this.selectOptionArr=[];
            this.onlyTableList=[];
            this.manyTableList=[];
            return 
        }
        // console.log('您选择了三级分类');
        const res=await this.axios.get(`categories/${this.cateId}/attributes`,{
            params:{
                sel:this.activeName
            }
        });
        console.log(res.data);
        
        if(res.meta.status==200){
            // 分类参数.处理res.data.attr_vals
            res.data.forEach(item=>{
                item.attr_vals=item.attr_vals?item.attr_vals.split(','):[];
                 item.inputVisible=false;
                 item.inputValue='';
            })
            console.log(res.data);
            if(this.activeName==='only'){
                this.onlyTableList=res.data;
            }else{
                this.manyTableList=res.data;
            }
            // console.log(this.onlyTableList);
            // console.log(this.manyTableList);
        }
      },
    //   处理选项发生改变的时候回调函数
    cascaderHandleChange(){
        //   console.log(this.selectOptionArr);
          this.getParams();
      },
    tabsHandleClick(){
        //   console.log(this.activeName);
          this.getParams();
    },

    // 对话框中的添加参数按钮
   addParamsSub(){
        this.$refs.addParamsRef.validate(async flag=>{
            if(!flag) return;
           console.log(123);
            const res=await this.axios.post(`categories/${this.cateId}/attributes`,{
                attr_name:this.addParamsForm.attr_name,
                attr_sel:this.activeName
            });
            if(res.meta.status==201){
                this.$mg.success(res.meta.msg);
                this.addParamsDialogVisible=false;
                this.getParams();
            }else{
                this.$mg.error('添加参数失败')
            }
        })
    },
    // 添加按钮对话框关闭时触发的事件
    addParamsDialogClose(){
        this.$refs.addParamsRef.resetFields();
    },   

    // 展示编辑按钮对话框的显示与隐藏事件
   
   
   
   
   async showEditParamsDialog(row){
        console.log(row);
        this.editParamsDialogVisible=true;
        const res=await this.axios.get(`categories/${this.cateId}/attributes/${row.attr_id}`);
        console.log(res.data);
        if(res.meta.status==200){
            this.editParamsForm=res.data;
        }
        console.log(this.editParamsForm);
        
    },
    // 编辑确定按钮
    editParamsSub(){
        // this.editParamsDialogVisible=false;
        this.$refs.editParamsRef.validate(async flag=>{
            if(!flag) return;
            const res=await this.axios.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,{
                attr_name:this.editParamsForm.attr_name,
                attr_sel:this.activeName
            });            
            if(res.meta.status==200){
                this.$mg.success('修改成功');
                this.getParams();
                this.editParamsDialogVisible=false;
            }
        })
    },
    // 编辑对话框关闭时触发的事件
    editParamsDialogClose(){
        this.$refs.editParamsRef.resetFields();
    },
    // 删除按钮的操作
    removeParams(row){
        
        this.$cfm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
        //   确定删除
        const res=await this.axios.delete(`categories/${this.cateId}/attributes/${row.attr_id}`);
        if(res.meta.status==200){
            this.$mg.success('删除成功!');
            this.getParams();
        }
        }).catch(() => {
          this.$mg({
            type: 'info',
            message: '已取消删除'
          });          
        });

    },
  
    // 输入框在键盘按下,回车,鼠标失去焦点之后触发的事件
    async handleInputConfirm(row){
        // 判断输入框的值
        if(row.inputValue.trim().length==0){
            row.inputValue='';
            row.inputVisible=false;
            console.log('输入不合法');
            // this.$mg.error('输入不合法');
            return
        }
        // 更新页面将数据追加到数组中,更新页面
        row.attr_vals.push(row.inputValue);
        this.editParamsAttr(row);
    },
    // tag按钮显示
    showInput(row){
        row.inputVisible=true; 
        // 打开标签之后自动获得焦点,保证页面dom渲染完毕之后调用该函数
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },

    // 删除参数下面的属性公共方法
    async editParamsAttr(row){
        const res=await this.axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
            attr_name:row.attr_name,
            attr_sel:this.activeName,
            attr_vals:row.attr_vals.join(',')
        });
        if(res.meta.status==200){
            row.inputValue='';
            row.inputVisible=false;
            this.$mg.success('更新属性成功!');
        }
    },

    // tag标签上面的删除按钮事件
    async removeAttr(i,row){
        console.log(i);
        row.attr_vals.splice(i,1);
        console.log(row.attr_vals);
        
        this.editParamsAttr(row);
    }
  
  },
    //计算属性用于判断按钮是否能够点击
  computed:{
      isBtnDisable(){
          if(this.selectOptionArr.length==3){
              return false;
          }
          return true;
      },
      cateId(){
          if(this.selectOptionArr.length==3){
              return this.selectOptionArr[2]
          }
          return null
      }
  },

  created () {
      this.getcascaderList();
  }
}
</script>

<style lang='less' scoped>

</style>
